package org.ns.tomdog.config;

import org.ns.tomdog.config.error.ServerConfigParseException;
import org.ns.tomdog.server.support.ServletWrapper;
import org.ns.tomdog.servlet.HttpServlet;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Web配置
 * webapp/WEB-INF/web.xml
 */
public class WebConfig extends XmlConfigParse {

    public WebConfig(File webConfigPath, ClassLoader classLoader) throws ServerConfigParseException {
        super(webConfigPath, classLoader);
    }

    private List<ServletWrapper> servletWrappers;
    @Override
    public void parse() {
        List<ServletWrapper> servletWrappers = new ArrayList<ServletWrapper>();
        parse("servlet", null, (servletNode)->{
            try {
                String name = servletNode.getAttribute("name"); // servlet名
                Class<HttpServlet> aClass = getClass(servletNode, HttpServlet.class); // servlet 实现
                List<String> mappers = parseToList("mapper", servletNode, (mapperNode)->{
                    String path = mapperNode.getAttribute("path");
                    if (path != null && path.length() > 0) {
                        return path;
                    }
                    return null;
                });
                HttpServlet httpServlet = aClass.newInstance();
                ServletWrapper servletWrapper = new ServletWrapper(name, httpServlet, mappers);
                servletWrappers.add(servletWrapper);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        this.servletWrappers = servletWrappers;
    }

    public List<ServletWrapper> getServletWrappers() {
        return servletWrappers;
    }
}
